package mop.gui.admin;

import java.sql.Timestamp;
import java.text.DateFormat;
import java.util.Date;
import java.util.List;
import mop.controller.ChangeClockController;
import mop.controller.CreateUserController;
import mop.gui.GUI;
import mop.model.user.UserTypeInterface;

/**
 * Window for admins.
 *
 * @author  MOP Team 7
 */
public class AdminWindow extends javax.swing.JFrame {

    /**
     * Empty constructor.
     */
    public AdminWindow() {
        initComponents();
    }

    /**
     * Constructor.
     *
     * @param   gui
     * @param   changeClockController
     * @param   createUserController
     * @effect  Sets the gui object.
     * @effect  Sets the controllers.
     * @effect  Loads the user types into the combobox.
     */
    public AdminWindow(GUI gui, ChangeClockController changeClockController, CreateUserController createUserController)
    {
        initComponents();
        setGui(gui);

        // Set controllers
        this.changeClockController = changeClockController;
        this.createUserController = createUserController;

        // Load user types
        this.userTypes = createUserController.getUserTypes();
        for (UserTypeInterface u : this.userTypes)
            this.cmbUserType.addItem(u.getId());

        // Set clock
        this.setDateTime(changeClockController.getVirtualTime());
    }

    /***************************************************************************
     *                          GUI reference
     ***************************************************************************/

    private GUI gui;

    /**
     * Sets the GUI.
     *
     * @param   gui
     * @post    gui is set.
     */
    private void setGui(GUI gui)
    {
        this.gui = gui;
    }

    /**
     * Returns the GUI reference.
     *
     * @return  this.gui
     */
    public GUI getGui()
    {
        return this.gui;
    }

    /***************************************************************************
     *                          User Types
     ***************************************************************************/

    private List<UserTypeInterface> userTypes;

    /***************************************************************************
     *                          Controllers
     ***************************************************************************/

    private ChangeClockController changeClockController;
    private CreateUserController createUserController;

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        txtUserName = new javax.swing.JTextField();
        lblName = new javax.swing.JLabel();
        btnCreateUser = new javax.swing.JButton();
        lblType = new javax.swing.JLabel();
        cmbUserType = new javax.swing.JComboBox();
        jPanel2 = new javax.swing.JPanel();
        btnTime = new net.sourceforge.jcalendarbutton.JTimeButton();
        btnDate = new org.sourceforge.jcalendarbutton.JCalendarButton();
        txtClock = new javax.swing.JTextField();
        btnAdjustClock = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Administration");

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Create User"));

        lblName.setText("User Name");

        btnCreateUser.setText("Create");
        btnCreateUser.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnCreateUserActionPerformed(evt);
            }
        });

        lblType.setText("User Type");

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(btnCreateUser, javax.swing.GroupLayout.DEFAULT_SIZE, 270, Short.MAX_VALUE)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(cmbUserType, javax.swing.GroupLayout.PREFERRED_SIZE, 137, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(lblType))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(lblName)
                            .addComponent(txtUserName, javax.swing.GroupLayout.PREFERRED_SIZE, 127, javax.swing.GroupLayout.PREFERRED_SIZE))))
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lblType)
                    .addComponent(lblName))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(cmbUserType, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(txtUserName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(btnCreateUser)
                .addContainerGap())
        );

        jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder("Adjust Clock"));

        btnTime.addPropertyChangeListener(new java.beans.PropertyChangeListener() {
            public void propertyChange(java.beans.PropertyChangeEvent evt) {
                btnTimestartChange(evt);
            }
        });

        btnDate.addPropertyChangeListener(new java.beans.PropertyChangeListener() {
            public void propertyChange(java.beans.PropertyChangeEvent evt) {
                btnDatestartChange(evt);
            }
        });

        txtClock.setEditable(false);
        txtClock.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusLost(java.awt.event.FocusEvent evt) {
                txtClockFocus(evt);
            }
        });

        btnAdjustClock.setText("Create");
        btnAdjustClock.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnAdjustClockActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(btnAdjustClock, javax.swing.GroupLayout.DEFAULT_SIZE, 270, Short.MAX_VALUE)
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addComponent(txtClock, javax.swing.GroupLayout.DEFAULT_SIZE, 216, Short.MAX_VALUE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btnDate, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btnTime, javax.swing.GroupLayout.PREFERRED_SIZE, 21, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap())
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(txtClock, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btnDate, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btnTime, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(btnAdjustClock)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jPanel2, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jPanel1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnCreateUserActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCreateUserActionPerformed
        try {
            String name = this.txtUserName.getText();
            UserTypeInterface type = this.userTypes.get(this.cmbUserType.getSelectedIndex());
            createUserController.createUser(type, name);
            gui.handleSuccess("User created!");
            gui.getMainWindow().update();
        } catch (Throwable exception) {
            gui.handleError(exception);
        }
}//GEN-LAST:event_btnCreateUserActionPerformed

    private void btnTimestartChange(java.beans.PropertyChangeEvent evt) {//GEN-FIRST:event_btnTimestartChange
        if (evt.getNewValue() instanceof Date)
            setDateTime((Date)evt.getNewValue());
}//GEN-LAST:event_btnTimestartChange

    private void btnDatestartChange(java.beans.PropertyChangeEvent evt) {//GEN-FIRST:event_btnDatestartChange
        if (evt.getNewValue() instanceof Date)
            setDateTime((Date)evt.getNewValue());
}//GEN-LAST:event_btnDatestartChange

    private void txtClockFocus(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_txtClockFocus
        setDateTime(txtClock.getText());
}//GEN-LAST:event_txtClockFocus

    private void btnAdjustClockActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAdjustClockActionPerformed
        try {
            // Parse time/date.
            Timestamp clock = new Timestamp(this.getDateTime().getTime());
            changeClockController.setVirtualTime(clock);
            gui.handleSuccess("Clock changed!");
            gui.getMainWindow().update();
        } catch (Throwable exception) {
            gui.handleError(exception);
        }
    }//GEN-LAST:event_btnAdjustClockActionPerformed

    private DateFormat dateTimeFormat = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.SHORT);
    
    /**
     * Validate and set the datetime field on the screen given a datetime string.
     * @param dateTime The datetime string
     */
    public void setDateTime(String dateTimeString)
    {
        Date dateTime = null;
        try
        {
            if ((dateTimeString != null) && (dateTimeString.length() > 0))
                dateTime = dateTimeFormat.parse(dateTimeString);
	}
        catch (Exception e)
        {
            dateTime = null;
        }
        this.setDateTime(dateTime);
    }

    /**
     * Validate and set the datetime field on the screen given a date.
     * @param dateTime The datetime object
     */
    public void setDateTime(Date dateTime)
    {
        String dateTimeString = "";
        if (dateTime != null)
            dateTimeString = dateTimeFormat.format(dateTime);
        txtClock.setText(dateTimeString);
        btnDate.setTargetDate(dateTime);
        btnTime.setTargetDate(dateTime);
    }


    /**
     * Returns the clock date & time as a Date object.
     *
     * @return  clock as Date object
     */
    public Date getDateTime()
    {
        Date dateTime = null;
        String dateTimeString = txtClock.getText();

        try
        {
            if ((dateTimeString != null) && (dateTimeString.length() > 0))
                dateTime = dateTimeFormat.parse(dateTimeString);
	}
        catch (Exception e)
        {
            dateTime = null;
        }

        return dateTime;
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnAdjustClock;
    private javax.swing.JButton btnCreateUser;
    private org.sourceforge.jcalendarbutton.JCalendarButton btnDate;
    private net.sourceforge.jcalendarbutton.JTimeButton btnTime;
    private javax.swing.JComboBox cmbUserType;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JLabel lblName;
    private javax.swing.JLabel lblType;
    private javax.swing.JTextField txtClock;
    private javax.swing.JTextField txtUserName;
    // End of variables declaration//GEN-END:variables

}
